package org.spring.config.server.controller;

import java.util.List;

import org.spring.config.server.dao.ProDao;
import org.spring.config.server.model.Properties;
import org.spring.config.server.page.table.PageTableHandler;
import org.spring.config.server.page.table.PageTableHandler.CountHandler;
import org.spring.config.server.page.table.PageTableHandler.ListHandler;
import org.spring.config.server.page.table.PageTableRequest;
import org.spring.config.server.page.table.PageTableResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/pro")
public class ProController {

    @Autowired
    private ProDao dictDao;

    @PostMapping
    public Properties save(@RequestBody Properties properties) {
        dictDao.save(properties);
        return properties;
    }

    @GetMapping("/{id}")
    public Properties get(@PathVariable Long id) {
        return dictDao.getById(id);
    }

    @PutMapping
    public Properties update(@RequestBody Properties properties) {
        dictDao.update(properties);
        return properties;
    }

    @GetMapping(params = {"start", "length"})
    public PageTableResponse list(PageTableRequest request) {
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return dictDao.count(request.getParams());
            }
        }, new ListHandler() {

            @Override
            public List<Properties> list(PageTableRequest request) {
                return dictDao.list(request.getParams(), request.getOffset(), request.getLimit());
            }
        }).handle(request);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        dictDao.delete(id);
    }

    @GetMapping(params = "type")
    public List<Properties> listByType(String type) {
        return dictDao.listByType(type);
    }
}
